<template>
  <div>
    <!-- 使用 el-card 包裹表格 -->
    <el-card class="box-card" style="min-height: 350px">
      <div slot="header" class="clearfix">
        <span>调休申请信息</span>
        <!-- 申请按钮 -->
        <el-button
            type="primary"
            style="float: right;"
            @click="handleApply"
        >
          申请
        </el-button>
      </div>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="最晚开始时间">
          <el-date-picker
              v-model="queryParams.startTime"
              type="date"
              placeholder="选择开始时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="最早结束时间">
          <el-date-picker
              v-model="queryParams.endTime"
              type="date"
              placeholder="选择结束时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.state" placeholder="请选择状态">
            <el-option label="未提交" :value="0"></el-option>
            <el-option label="申请过程中" :value="1"></el-option>
            <el-option label="申请完成" :value="2"></el-option>
            <el-option label="全部" :value="null"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- el-table 显示数据 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%; "
          v-loading="loading"
      >
        <!-- 表格列定义 -->
        <!--        <el-table-column prop="id" label="主键ID" width="80"></el-table-column>-->
        <el-table-column
            prop="startTime"
            label="调休开始时间"
            width="168"
        ></el-table-column>
        <el-table-column
            prop="endTime"
            label="调休结束时间"
            width="168"
        ></el-table-column>
        <el-table-column
            prop="employeeName"
            label="申请人"
            width="120"
        ></el-table-column>
        <el-table-column
            prop="reason"
            label="申请理由"
            width="200"
        ></el-table-column>
        <el-table-column
            prop="approverId"
            label="审批人ID"
            width="90"
        ></el-table-column>
        <el-table-column prop="state" label="当前状态" width="120">
          <template slot-scope="scope">
            <!-- 根据 state 值显示不同的状态文本 -->
            <el-tag
                :type="getStateTagType(scope.row.state)"
                size="small"
            >
              {{ getStateLabel(scope.row.state) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="remarks"
            label="反馈信息"
            width="150"
        ></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button
                type="danger"
                size="small"
                :disabled="scope.row.state === 2"
                @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          style="margin-top: 20px; text-align: right"
      >
      </el-pagination>
    </el-card>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="40%"
        @close="handleDialogClose"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <el-form-item label="调休开始时间" prop="startTime">
          <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
              clearable
              :disabled = "formData.state !== 0"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="调休结束时间" prop="endTime">
          <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
              clearable
              :disabled = "formData.state !== 0"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input
              v-model="formData.reason"
              type="textarea"
              placeholder="请输入申请理由（可选）"
              :disabled = "formData.state !== 0"
          ></el-input>
        </el-form-item>
        <el-form-item label="审批人" prop="approverId">
          <el-select
              v-model="formData.approverId"
              placeholder="请选择审批人"
              :disabled = "formData.state !== 0"
          >
            <el-option
                v-for="approver in approvers"
                :key="approver.employeeId"
                :label="approver.employeeName"
                :value="approver.employeeId"
                :disabled = "formData.state !== 0"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose"  :disabled = "formData.state !== 0">取消</el-button>
        <el-button type="primary" @click="formData.state = 0; handleSave()"  :disabled = "formData.state !== 0">保存</el-button>
        <el-button
            type="success"
            @click="formData.state = 1; handleSave()"
            :disabled="formData.state === 2 "
        >
          确认并提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompOffList,
  saveCompOffApply,
  deleteCompOffApply
} from '@/api/compoffApi';
import { getEmployeeInfoByRoleanddepartment } from "@/api/employeeApi";

export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        startTime: null,
        endTime: null,
        state: null,
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      dialogVisible: false,
      dialogTitle: "编辑申请",
      formData: {
        id: null,
        startTime: null,
        endTime: null,
        reason: "",
        approverId: null,
        employId: window.sessionStorage.getItem("empId"),
        state: 0,
      },
      formRules: {
        startTime: [{ required: false, message: "请选择开始时间", trigger: "change" }],
        endTime: [{ required: false, message: "请选择结束时间", trigger: "change" }],
        approverId: [{ required: false, message: "请选择审批人", trigger: "change" }],
      },
      approvers: [], // 存储审批人列表
    };
  },
  async created() {
    await this.fetchApprovers();
    await this.fetchData();
  },
  methods: {
    async fetchApprovers() {
      try {
        const response = await getEmployeeInfoByRoleanddepartment(3, 1);
        console.log(response)
        this.approvers = response.data;
      } catch (error) {
        this.$message.error('获取审批人失败: ' + (error.message || '未知错误'));
        console.error('审批人加载失败:', error);
      }
    },
    // 获取数据的方法
    async fetchData() {
      this.loading = true;

      const params = {
        employId: window.sessionStorage.getItem("empId"),
        ...this.queryParams,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
      };

      try {
        const result = await getCompOffList(params);
        if (result.code === 200) {
          this.tableData = result.data.list;
          // console.log(this.tableData);
          this.pagination.total = result.data.total;
          this.pagination.pageNum = result.data.pageNum;
          this.pagination.pageSize = result.data.pageSize;
        }
      } catch (error) {
        console.error("请求失败:", error);
      } finally {
        this.loading = false;
      }
    },
    // 处理分页大小变化
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize;
      this.fetchData();
    },
    // 处理分页页码变化
    handleCurrentChange(newPage) {
      this.pagination.pageNum = newPage;
      this.fetchData();
    },
    // 根据 state 值返回对应的状态标签类型
    getStateTagType(state) {
      switch (state) {
        case 0:
          return "info"; // 未提交
        case 1:
          return "warning"; // 申请过程中
        case 2:
          return "success"; // 申请完成
        default:
          return "info";
      }
    },
    // 根据 state 值返回对应的状态文本
    getStateLabel(state) {
      switch (state) {
        case 0:
          return "未提交";
        case 1:
          return "申请过程中";
        case 2:
          return "申请完成";
        default:
          return "";
      }
    },
    // 删除操作
    async handleDelete(id) {
      try {
        await this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const result = await deleteCompOffApply(id);
        if (result.code === 200) {
          this.$message.success("删除成功");
          this.fetchData(); // 刷新数据
        } else {
          this.$message.error("删除失败：" + result.message);
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info("已取消删除");
        } else {
          console.error("删除失败:", error);
          this.$message.error("删除请求失败");
        }
      }
    },
    // 打开编辑弹窗
    handleEdit(row) {
      this.dialogTitle = "编辑申请";
      this.formData = { ...row }; // 填入初始数据
      this.dialogVisible = true;
    },
    // 打开申请弹窗
    handleApply() {
      this.dialogTitle = "新增申请";
      this.formData = {
        id: null,
        startTime: null,
        endTime: null,
        reason: "",
        approverId: null,
        employeeId: window.sessionStorage.getItem("empId"),
        state: 0,
      };
      this.dialogVisible = true;
    },
    // 关闭弹窗
    handleDialogClose() {
      this.dialogVisible = false;
      this.$refs.formRef.resetFields(); // 清空表单校验
    },
    // 提交并保存（调用 save 接口）
    async handleSave() {
      // 确认并保存时，至少需要一个字段不为空
      if (
          !this.formData.startTime ||
          !this.formData.endTime ||
          !this.formData.approverId
      ) {
        this.$message.warning("请至少填写开始时间、结束时间或选择审批人");
        return;
      }

      // console.log(this.formData);

      try {
        const result = await saveCompOffApply(this.formData);
        if (result.code === 200) {
          this.$message.success("保存成功");
          this.fetchData();
          this.handleDialogClose();
        } else {
          this.$message.error("保存失败：" + result.message);
        }
      } catch (error) {
        console.error("保存失败:", error);
        this.$message.error("保存请求失败");
      }
    },
  },
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.clearfix {
  font-size: 16px;
  font-weight: bold;
}

.demo-form-inline {
  margin-bottom: 20px;
}
</style>